package com.mg.pluginwebservice;

import com.alibaba.fastjson.JSONObject;
import com.mg.model.Model;
import com.mg.model.Param;
import com.mg.model.Port;
import com.mg.objects.Workspace;
import com.mg.pluginexample2.Model2;
import com.mg.pluginexample2.ModuleBase;
import com.mg.pluginwebservice.entity.ParamNode;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class AssistXmlFormTmp extends ModuleBase {

    public AssistXmlFormTmp(int nID) {
        super(nID);
    }

    public String GetGroupName() {
        return "基础模块";
    }

    public String GetName() {
        return "XML文件生成";
    }

    public String GetDescription() {
        return "";
    }

    public boolean OnAttach(Port portFrom, Port portTo) {
        try {
            int i = FindPort(portFrom, false);
            if (i != -1)
                return true;
            i = FindPort(portTo, true);
            if (i == -1)
                return false;
            if (portFrom.GetType() != portTo.GetType())
                return false;
            ArrayList<Param> alParam = new ArrayList<Param>();
            portFrom.GetModule().GetOutputParam(portFrom, alParam);
            if (alParam.size() < 2)
                return false;

        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }

        return true;
    }

    public boolean OnDetach(Port portFrom, Port portTo) {
        if (!super.OnDetach(portFrom, portTo))
            return false;
        try {
            int i = FindPort(portTo, true);
            if (i == -1)
                return true;
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    //用于 参数->XML 等
    public int GetParam(ArrayList<Param> alParam) {
        try {
            super.GetParam(alParam);

            Model2 model = ((Model2) m_model);
            alParam.add(new Param("InputTemplateFile", m_strInputTemplateFile, "模版文件路径", "", "输入", Param.EditType.File, "模板文件(*.xml)|*.xml"));
            alParam.add(new Param("ParamFile", m_strParamFile, "参数文件路径", "", "输入", Param.EditType.File, "模板文件(*.xml)|*.xml"));
            alParam.add(new Param("Code", m_strCode, "Param", "", "输入", Param.EditType.Default));
            alParam.add(new Param("OutputTemplateFile", m_strOutputTemplateFile, "文件路径", "", "输出", Param.EditType.File, "模板文件(*.xml)|*.xml"));

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return alParam.size();
    }

    public boolean OnParamChanged(ArrayList<Param> alParam, int nIndex, Object objValue) {
        return super.OnParamChanged(alParam, nIndex, objValue);
    }

    //用于 XML->参数 等
    public int SetParam(final ArrayList<Param> alParam) {
        int i = super.SetParam(alParam);
        try {
            m_strInputTemplateFile = (String) alParam.get(i++).m_objValue;
            m_strParamFile = (String) alParam.get(i++).m_objValue;
            m_strCode = (String) alParam.get(i++).m_objValue;
            m_strOutputTemplateFile = (String) alParam.get(i++).m_objValue;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return i;
    }

    @SuppressWarnings("static-access")
    public boolean Execute() {
        boolean flag = true;

        StringBuffer sb = new StringBuffer();

        String strTemplateFile = m_strInputTemplateFile;
        if (!new File(strTemplateFile).isAbsolute()) {
            strTemplateFile = new File(m_model.m_strFileName).getParent() + "/" + m_strInputTemplateFile;
        }

        ParamNode node = getParamNode(m_paramNodes, m_strCode);
        if (node == null) {
            m_model.OutputLog(Model.LogLevel.Error, String.format("NO PARAM NODE"));
            return false;
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(strTemplateFile), "gb2312"));
            String tmp = reader.readLine();
            while (tmp != null) {
                sb.append(node.assistXmlData(tmp));
                tmp = reader.readLine();
            }
            String outFile = m_strOutputTemplateFile;

            if (!new File(outFile).isAbsolute()) {
                outFile = new File(m_model.m_strFileName).getParent() + "/" + m_strOutputTemplateFile;
            }

            File file = new File(outFile);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file), "gb2312"));
            writer.write(sb.toString());
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        OnParamChanged();
        return flag;
    }

    private ParamNode getParamNode(List<ParamNode> m_paramNodes, String code) {
        for (ParamNode node : m_paramNodes) {
            if (node.getCode().equalsIgnoreCase(code)) {
                return node;
            }
        }
        return null;
    }

    public boolean OnBeforeExecute() {
        try {
            Model2 model = ((Model2) m_model);
            m_paramNodes = new ArrayList<ParamNode>();
            //--------------------------------------------------------------------------------------------------------------
            //加载模板到当前工作空间
            String strTemplateFile = m_strParamFile;
            if (!new File(strTemplateFile).isAbsolute())
                strTemplateFile = new File(m_model.m_strFileName).getParent() + "/" + m_strParamFile;
            if (!new File(strTemplateFile).exists())
                throw new AssertionError();
            SAXReader saxr = new SAXReader();
            Document doc = saxr.read(new InputStreamReader(new FileInputStream(strTemplateFile), "gb2312"));

            List<Element> listElement = doc.selectNodes("Workspace/Nodes");
            Iterator<Element> it = listElement.iterator();
            while (it.hasNext()) {
                Element e = it.next();
                String code = e.attributeValue("Param");
                String name = e.attributeValue("Name");
                String location = e.attributeValue("Location");
                String shpName1 = e.attributeValue("City");
                String shpName2 = e.attributeValue("Label");
                String shpName3 = e.attributeValue("Line");
                ParamNode paramNode = new ParamNode(code, name, location, shpName1, shpName2, shpName3);
                m_paramNodes.add(paramNode);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public int GetOutputParam(Port port, ArrayList<Param> alParam) {
        int i = FindPort(port, false);
        return alParam.size();
    }

    String m_strInputTemplateFile;
    String m_strParamFile;
    String m_strCode;
    List<ParamNode> m_paramNodes;

    String m_strOutputTemplateFile;
}
